var express = require('express');
var router = express.Router();
var Mongodb = require('../../database/mongodb');
var counters = require('../../routes/common/counter');
var encryptUtil = require('../../utils/encryptUtil');
const https = require('https');
const request = require('request')
const BizResult = require("../../service/BizResult");
let utils = require('./../../utils/utils');
var axios = require('axios');
//通用数据操作服务.

function synNewUser(ccUser) {
  let conditions = {
    loginName: ccUser.loginName
  }
  Mongodb.findOne('users', conditions, (err, docs) => {
    if(!err && docs){
      // 已存在不处理
      console.log(ccUser.loginName + "已存在")
    } else {
      console.log('保存新用户' + ccUser.userName)
      delete ccUser.orgId
      delete ccUser.roleIds
      delete ccUser.userPicId
      Mongodb.save("users", ccUser, (err, docs) => {
        console.log(docs)
      })
    }
  });
}

function synServer(item) {
  delete item.orgId
  delete item.updateHistory
  delete item.createUser
  delete item.createDate
  Mongodb.save("server", item, (err, docs) => {
    console.log(docs)
  })
}

function synBacklog(item) {
  Mongodb.save("backlog", item, (err, docs) => {
    console.log(docs)
  })
}

function synRushJob(item) {
  delete item.itemId
  Mongodb.save("rushJobs", item, (err, docs) => {
    console.log(docs.name)
  })
}

function synsharedocs(item) {
  Mongodb.save("sharedocs", item, (err, docs) => {
    console.log(docs)
  })
}

function synshareCatalog(item) {
  Mongodb.save("shareCatalog", item, (err, docs) => {
    console.log(docs)
  })
}

function synshareView(item) {
  Mongodb.save("shareView", item, (err, docs) => {
    console.log(docs)
  })
}

function synshareFavorite(item) {
  Mongodb.save("shareFavorite", item, (err, docs) => {
    console.log(docs)
  })
}

router.post('/time', function(req, res, next) {
  res.json(new Date().getTime())
  axios.post("http://10.20.32.112:5000/works/data/find/sharedocs", res.body).then((res) => {
    if (res.data) {
      res.data.forEach(item => {
        // synsharedocs(item)
      })
    }
  });
});

router.get('/version', function(req, res, next) {
  Mongodb.findOne('xtcs', { csName: 'H5_VERSION' }, function (err, docs) {
    if (err) {
      res.status(500).send(err);
    } else {
      res.json(docs);
    }
  });
});

/**
 * 判断是否节假日
 */
router.get('/holiday/:day', function (req, res, next) {
  https.get("https://tool.bitefu.net/jiari/?d=" + req.params.day, (response) => {
    var body = '';
    response.on('data',function(data){
        body += data;
    }).on('end', function(){          
        res.json(body)
    });
  }).on("error", function (err) {  
    console.log(err)
  }); 
});

/**
 * 加密
 */
router.post('/encrypt', function (req, res, next) {
  let condition = req.body;
  let encryStr = encryptUtil.encrypt(condition.str, "5tJByL2Hkt7rABzCdMkEn5YXfxG81IjK");
  res.send(encryStr);
});

router.post('/search', function(req, res, next) {
  request({
    url: 'http://10.51.101.79:9010/common/get',
    method: "POST",
    json: true,
    headers: {"content-type": "application/json"},
    body: req.body
  }, function(error, response, body) {
    if (!error && response.statusCode == 200) {
      res.json(body)
    } else {
      res.json(error)
    }
    
  });
});

/**
 * 解密
 */
 router.post('/decrypt', function (req, res, next) {
  let condition = req.body;
  let encryStr = encryptUtil.decrypt(condition.str, "5tJByL2Hkt7rABzCdMkEn5YXfxG81IjK");
  res.send(encodeURIComponent(encryStr));
});

/**
 * 查询所有数据
 */
router.get('/aggregate/:name', function (req, res, next) {
  var tbName = req.params.name;
  let condition = req.body;
  Mongodb.aggregate(tbName, condition, function (err, docs) {
    if (err) {
      res.send("查询失败");
    } else {
      res.json(docs);
    }
  });
});

/**
 * 获取自增序号
 */
router.post('/counter/:key', function (req, res, next) {
  var key = req.params.key;
  counters.getNextSequenceValue(key, (value) => {
    res.json(BizResult.success(value));
  });
});

/**
 * 取消自增序号
 */
router.post('/recounter/:key', function (req, res, next) {
  var key = req.params.key;
  counters.reNextSequenceValue(key, (value) => {
    res.json(BizResult.success(value));
  });
});

/**
 * 保存
 */
router.post('/save/:name', function (req, res, next) {
  var obj = req.body;
  var tbName = req.params.name;
  Mongodb.save(tbName, obj, function (err, docs) {
    if (err) {
      console.log(err)
      res.status(500).send("保存失败")
    } else {
      res.json(BizResult.success(docs));
    }
  });
});

/**
 * 批量保存
 */
router.post('/saveDocs/:name', function (req, res, next) {
  var docs = req.body;
  var tbName = req.params.name;
  Mongodb.saveDocs(tbName, docs, function (err, docs) {
    if (err) {
      res.status(500).send("保存失败");
    } else {
      res.json(BizResult.success(docs));
    }
  });
});



/**
 * 批量删除
 */
router.post('/deleteDocs/:name', function (req, res, next) {
  var where = req.body;
  var tbName = req.params.name;
  Mongodb.remove(tbName, where, function (err, docs) {
    if (err) {
      res.status(500).send("删除失败");
    } else {
      res.json(docs);
    }
  });
});

/**
 * 删除
 */
router.get('/delete/:name/:id', function (req, res, next) {
  var where = {
    _id: req.params.id
  };
  var tbName = req.params.name;
  Mongodb.remove(tbName, where, function (err, docs) {
    if (err) {
      res.status(500).send("删除失败");
    } else {
      res.json(docs);
    }
  });
});

/**
 * 更新项目
 */
router.post('/update/:name/:id', function (req, res, next) {
  var where = {
    _id: req.params.id
  };
  var tbName = req.params.name;

  var fields = req.body;
  Mongodb.update(tbName, where, fields, function (err, docs) {
    if (err) {
      console.log(err)
      res.status(500).send("更新失败");
    } else {
      res.json(docs);
    }
  });
});

/**
 * 更新项目
 */
router.post('/updateDelete/:name/:id', function (req, res, next) {
  var where = {
    _id: req.params.id
  };
  var tbName = req.params.name;

  var fields = req.body;
  Mongodb.updatePull(tbName, where, fields, function (err, docs) {
    if (err) {
      res.status(500).send("更新失败");
    } else {
      res.json(docs);
    }
  });
});

/**
 * 更新项目
 */
router.post('/updateAdd/:name/:id', function (req, res, next) {
  var where = {
    _id: req.params.id
  };
  var tbName = req.params.name;

  var fields = req.body;
  Mongodb.updateAdd(tbName, where, fields, function (err, docs) {
    if (err) {
      res.status(500).send("更新失败");
    } else {
      res.json(docs);
    }
  });
});

/**
 * 批量更新项目
 */
router.post('/updateDocs/:name', function (req, res, next) {
  var tbName = req.params.name;
  var condition = req.body;
  Mongodb.update(tbName, condition.where, condition.doc, function (err, docs) {
    if (err) {
      res.status(500).send("更新失败");
    } else {
      res.json(docs);
    }
  });
});

/**
 * 查询所有数据
 */
router.get('/findAll/:name', function (req, res, next) {
  var tbName = req.params.name;
  Mongodb.find(tbName, {}, {}, {}, function (err, docs) {
    if (err) {
      res.status(500).send("查询失败");
    } else {
      res.json(docs);
    }
  });
});


/**
 * 分页查询
 */
router.post('/findPage/:name', function (req, res, next) {
  let tbName = req.params.name;
  let queryParam = req.body;
  let result = {}
  let conditions = {}
  if (queryParam.condition) {
    conditions = processCondtion(queryParam.condition)
  } else {
    conditions = processCondtion(queryParam)
  }
  console.log(conditions);
  Mongodb.findPage(tbName, conditions, queryParam.options, (err, docs) => {
    if (err) {
      console.log(err)
      res.status(500).send("查询失败");
    } else {
      Mongodb.count(tbName, conditions, (err, count) => {
        if (err) {
          console.log(err)
          res.status(500).send("查询失败");
        } else {
          result.total = count;
          result.pageSize = queryParam.options.pageSize;
          result.pageNum = queryParam.options.pageNum;
          result.content = docs;
          res.json(BizResult.success(result));
        }
      });
    }
  });
});

function processCondtion (condition) {
  let result = {}
  for (let name in condition) {
    if (name === 'like') {
      for (let c in condition[name]) {
        if (condition.like[c]) {
          result[c] = new RegExp(condition.like[c], 'i')
        }
      }
    } else if (Array.isArray(condition[name])) {
      result[name] = []
      for (let index = 0; index < condition[name].length; index++) {
        const element = condition[name][index]
        result[name].push(processCondtion(element))
      }
    } else {
      result[name] = condition[name]
    }
  }
  return result
}

/**
 * 查询结果总数.
 */
router.post('/findCount/:name', function (req, res, next) {
  let tbName = req.params.name;
  let queryParam = req.body;
  let conditions = {}
  if (queryParam.condition) {
    conditions = processCondtion(queryParam.condition)
  } else {
    conditions = processCondtion(queryParam)
  }
  Mongodb.count(tbName, conditions, function (err, docs) {
    if (err) {
      res.status(500).send("查询失败");
    } else {
      res.json(BizResult.success(docs));
    }
  });
});

// 按排序规则获取最近一条记录
router.post('/findTopOne/:name', function (req, res, next) {
  var tbName = req.params.name;
  let conditions = req.body;
  Mongodb.find(tbName, conditions.query, null, conditions.sort, function (err, docs) {
    if (err) {
      res.status(500).send("查询失败");
    } else {
      res.json(BizResult.success(docs || []));
    }
  });
})

/**
 * 按条件查询
 */
router.post('/find/:name', function (req, res, next) {
  var tbName = req.params.name;
  let queryParam = req.body;
  let conditions = {}
  let options = queryParam.options || {}
  if (queryParam.condition) {
    conditions = processCondtion(queryParam.condition)
  } else {
    conditions = processCondtion(queryParam)
  }
  Mongodb.find(tbName, conditions, options.fields || null, options.sort || null, function (err, docs) {
    if (err) {
      res.status(500).send(err);
    } else {
      res.json(BizResult.success(docs));
    }
  });
});

/**
 * 按条件查询
 */
router.post('/findTree/:name', function (req, res, next) {
  var tbName = req.params.name;
  let queryParam = req.body;
  let options = queryParam.options || {}
  queryParam.condition = processCondtion(queryParam.condition)
  console.log(queryParam)
  Mongodb.find(tbName, queryParam.condition, options.fields || null, options.sort || null, function (err, docs) {
    if (err) {
      res.status(500).send(err);
    } else {
      res.json(BizResult.success(utils.arrayToTree(docs, options.tree)));
    }
  });
});

/**
 * 获取图片
 */
router.get('/find/imgs/:id', function (req, res, next) {
  let conditions = {
    '_id': req.params.id
  }
  Mongodb.findOne('imgs', conditions, function (err, docs) {
    if (docs && docs.type) {
      let base64Data
      if (docs.type.indexOf('image') !== -1) {
        base64Data = docs.content.replace(/^data:image\/\w+;base64,/, "");
      } else {
        base64Data = docs.content.replace(/^data:video\/\w+;base64,/, "");
      }
      let binaryData = new Buffer(base64Data, 'base64');
      res.writeHead('200', {'Content-Type': docs.type || 'image/jpeg'});
      res.end(binaryData, 'binary');
    } else {
      res.send(err);
    }
  });
})

/**
 * 查询单条记录.
 */
router.post('/findOne/:name', function (req, res, next) {
  var tbName = req.params.name;
  let conditions = req.body;
  Mongodb.findOne(tbName, conditions, function (err, docs) {
    if (err) {
      res.status(500).send("查询失败");
    } else {
      res.json(BizResult.success(docs));
    }
  });
});

/**
 * 分组查询
 */
router.post('/group/:name', function (req, res, next) {
  var tbName = req.params.name;
  let conditions = req.body;
  let model = Mongodb.getConnection(tbName);
  // 处理日期条件不生效问题
  processGroupCondtion(conditions)
  model.aggregate(conditions, function(err, docs){
    if(!err){
      res.json(BizResult.success(docs));
    } else {
      console.log(err)
      res.status(500).send(err)
    }
  });
});

/**
 * 分组查询
 */
router.post('/group1/:name', function (req, res, next) {
  var tbName = req.params.name;
  let conditions = req.body;
  let model = Mongodb.getConnection(tbName);
  model.aggregate(conditions, function(err, docs){
    if(!err){
      res.json(BizResult.success(docs));
    } else {
      console.log(err)
      res.status(500).send(err)
    }
  });
});

function processGroupCondtion (condition) {
  if (Array.isArray(condition)) {
    condition.forEach(item => {
      processGroupCondtion(item)
    })
  } else {
    for (let name in condition) {
      if (condition[name] instanceof Object) {
        processGroupCondtion(condition[name])
      } else if (isNaN(condition[name]) && !isNaN(Date.parse(condition[name]))) {
        condition[name] = new Date(condition[name])
      }
    }
  }
}

module.exports = router;